import socketserver
import time,os,hmac
__auther__='zhuifeng'
buff_size=1024
back_log=5
buffsize=1024
connect_key= b'aaaa'
class Myserver(socketserver.BaseRequestHandler):
    def auth_connect(self,*args):
        '''验证链接是否合法'''
        print("开始验证链接是否合法")
        msg = os.urandom(32)
        self.request.sendall(msg)
        print(msg)
        h = hmac.new(connect_key, msg)
        digest = h.hexdigest()  # 十六进制加密
        respone = self.request.recv(len(digest))
        print("加密的结果digest", digest.encode("utf-8"))
        print("返回结果respone", respone)
        return hmac.compare_digest(respone, digest.encode("utf-8"))
    def handle(self):
        try:
            print(self.request)
            print(self.client_address)
            if not self.auth_connect(self.request):
                print("链接不合法，直接关闭")
                self.request.close()
                return
            else:
                print("链接合法，开始发送消息")
            while True:
                data=self.request.recv(1024)
                if not data:break
                print(time.ctime(), "收到客户端%s发送的消息是%s," % (self.client_address, data))
                self.request.sendall(data.upper())
            self.request.close()
        except Exception:
            print(Exception)

if __name__ == '__main__':
    ip_port = ("localhost", 1234)
    server=socketserver.ThreadingTCPServer(ip_port,Myserver)
    server.serve_forever()